package com.kiwilss.aopdemo.ui.room.kotlin

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

/**
 * @author : Administrator
 * e-mail : kiwilss@163.com
 * time   : 2021/02/02
 *  desc   :
 */
@Database(entities = [User::class], version = 2, exportSchema = false)
abstract class AppDataBase : RoomDatabase() {

    abstract fun userDao(): UserDao

    companion object {
        //实例化
        private var instance: AppDataBase? = null
        fun getInstance(context: Context): AppDataBase {
            if (instance == null) {
                synchronized(AppDataBase::class) {
                    instance = Room.databaseBuilder(
                        context.applicationContext,
                        AppDataBase::class.java,
                        "user.db"//数据库名称
                    ).fallbackToDestructiveMigration()
                        .addMigrations(MIGRATION_USER_1_2)
                        .allowMainThreadQueries().build()
                }
            }
            return instance!!
        }

        //升级users表
        private val MIGRATION_USER_1_2 = object : Migration(1,2){
            override fun migrate(database: SupportSQLiteDatabase) {
                //表新增一列
                database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER NOT NULL DEFAULT 0")
                //删除表
//                database.execSQL("drop table users")
//                database.execSQL("delete database user.db")
            }

        }
    }


}